var entityCollection = require('./EntityCollection'),
    BaseFun = require('./Function'),
    FileDownload = require('./FileDownload'),
    formidable = require("formidable"),
    http = require('http'),
    FileCopy = require('./FileCopy'),
    BaseConst = require("./Const");
var fs = require("fs");
var unzip = require("unzip2");
var archiver = require('archiver');

//上传文件
exports.uploadFile = function(req, res) {
    var reviceData = {};
    var form = new formidable.IncomingForm();   //创建上传表单
    form.encoding = 'utf-8';        //设置编辑
    form.uploadDir = BaseConst.FilePath;    //设置上传目录
    form.keepExtensions = true;  //保留后缀
    form.maxFieldsSize = 20 * 1024 * 1024;   //单个表单域能够申请到的最大内存值，不是限定文件的大小。

    form.on('error', function(err) {
        if(err.message != "Request aborted"){
            var newErr = new Error();
            newErr.leval = 5;
            newErr.title = '文件上传失败';
            newErr.message = '文件解析错误';
            BaseFun.responseFun(res, newErr);
        }
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        var progress = {
            type: 'progress',
            bytesReceived: bytesReceived,
            bytesExpected: bytesExpected,
            uploadProgress: bytesReceived / req.headers['content-length']
        };

        reviceData['progress'] = progress.uploadProgress * 100 + '%';
    });

    form.on('field', function(name, value) {
        reviceData[name] = value;
    });

    form.on('file', function(name, file) {
        reviceData[name] = file;
    });

    form.on('end', function(file) {
        //如果传入了旧的文件路径，删除该文件
        if(reviceData.hasOwnProperty("DeleteFileName") && reviceData.DeleteFileName.trim() != ""){
            BaseFun.fileDeleteSync(BaseConst.FilePath + reviceData.DeleteFileName);
        }

        var strPath = reviceData.file.path.replace(/\\/g, "/");
        var intLastSymbol = strPath.lastIndexOf('/');
        var fileFullName = strPath.substring(intLastSymbol + 1, strPath.length);
        var fileName = fileFullName.substring(0, fileFullName.lastIndexOf('.'));
        var extendName = fileFullName.substring(fileFullName.lastIndexOf('.') + 1, fileFullName.length);
        var newFileName = fileFullName;
        //如果传入了文件名称，用传入的文件名称
        if(reviceData.hasOwnProperty("FileName")){
            newFileName = reviceData.FileName;
        }
        else{
            //否则用自动赋值的新文件名
            newFileName = fileName.split('_')[1];
        }
        var savePath = reviceData['file'].path;
        var newPath = BaseConst.FilePath + newFileName + "." + extendName;

        if(BaseFun.fileRenameSync(savePath, newPath)){
            reviceData.file.path = newFileName + "." + extendName;
        }
    });

    form.parse(req, function(err, fields, files) {
        if (err) {
            //在error事件中已经处理
        }
        else{
            BaseFun.responseFun(res, null, files);
        }
    });
};

//下载文件，从别的服务器下载文件
exports.downloadFile = function(req, res) {
    var parameter = req.body;
    var serverPath = parameter.ServerPath;              //文件服务器下载地址，包括IP、端口、Api
    var downloadFileName = parameter.DownloadFileName;  //文件服务器的文件全名

    var fileName = parameter.FileName;                  //本地保存文件名，可为空，为空时以源文件名称命名    
    var deleteFileName = parameter.DeleteFileName;      //本地要删除的文件名，可为空

    var socketId = parameter.SocketId;      //如果需要向前端发送下载过程信息，传入该值，通过Socket发送通知

    BaseFun.downloadFile(serverPath, downloadFileName, fileName, deleteFileName, socketId,
        function(err, file){
            if(err){
                var newErr = new Error();
                newErr.leval = 5;
                newErr.title = '下载失败';
                newErr.message = '未能连接上下载服务器';
                BaseFun.responseFun(res, newErr);
            }
            else{
                BaseFun.responseFun(res, null, file);
            }
        }
    );
};

//导出报表（Excel）
exports.createExcel = function(req, res){
    var parameter = req.body;
    var workbook = parameter.Workbook;
    if(workbook.CreatedBy == undefined || workbook.CreatedBy == null || workbook.CreatedBy === ''){
        workbook.CreatedBy = req.user.Code;
    }

    BaseFun.createExcel(workbook, function(err, newWorkbook){
        BaseFun.responseFun(res, err, newWorkbook);
    });
};

//获取文件流，从本服务器获取
exports.getFileStream = function(req, res) {
    var parameter = req.body;
    var fileName = parameter.FileName;

    var fileFullPath = BaseConst.FilePath + fileName;
    
    var fileDownload = new FileDownload(req, res);
    fileDownload.Download(fileFullPath);
};

//文件重命名
exports.fileRenames = function(req, res) {
    var newErr = new Error();
    newErr.leval = 5;
    newErr.title = '文件重命名失败';
    newErr.message = '';

    var parameter = req.body;

    var excuteCount = 0;
    for(var i=0; i<parameter.FilePaths.length; i++){
        BaseFun.fileRename(parameter.FilePaths[i].OldPath, parameter.FilePaths[i].NewPath, function(err){
            if (err) {
                newErr.message += "\r\n" + parameter.FilePaths[i].OldPath;
            }
            excuteCount++;
            if(excuteCount == parameter.FilePaths.length){
                if(newErr.message != ""){
                    newErr.message = "失败文件：" + newErr.message;
                    BaseFun.responseFun(res, newErr);
                }
                else{
                    BaseFun.responseFun(res, null, excuteCount);
                }
            }
        });
    }
};

//删除文件
exports.fileDeletes = function(req, res) {
    var newErr = new Error();
    newErr.leval = 5;
    newErr.title = '文件删除失败';
    newErr.message = '';

    var parameter = req.body;

    var excuteCount = 0;
    for(var i=0; i<parameter.FilePaths.length; i++){
        BaseFun.fileDelete(parameter.FilePaths[i], function(err){
            if (err) {
                newErr.message += "\r\n" + parameter.FilePaths[i];
            }

            excuteCount++;

            if(excuteCount == parameter.FilePaths.length){
                if(newErr.message != ""){
                    newErr.message = "失败文件：" + newErr.message;
                    BaseFun.responseFun(res, newErr);
                }
                else{
                    BaseFun.responseFun(res, null, excuteCount);
                }
            }
        });
    }
};

exports.fileUpload = function(req, res) {

    var reviceData = {};
    var form = new formidable.IncomingForm();
    form.uploadDir = './public/users/img/'; //上传目录
    form.keepExtensions = true; //保留后缀格式
    form.maxFieldsSize = 2 * 1024 * 1024; //文件大小

    form.on('error', function() {
        res.status(400).send({
            message: "文件解析错误"
        });
        res.json({
            message: "文件解析错误"
        });
    });

    form.on('field', function(name, value) {
        reviceData[name] = value;
    });

    form.on('file', function(name, file) {
        reviceData[name] = file;
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        var progress = {
            type: 'progress',
            bytesReceived: bytesReceived,
            bytesExpected: bytesExpected,
            uploadProgress: bytesExpected / req.headers['content-length']
        };

        reviceData['progress'] = progress.uploadProgress * 100 + '%';
    });

    form.on('end', function() {
        var str = reviceData['file'].path.replace(/\\/g, "/");
        var strArr = str.split('/');
        res.status(200).send({
            path: strArr[1] + '/' + strArr[2] + '/' + strArr[3],
            fullPath: reviceData['file'].path
        });
    });
    form.parse(req);
};

//获取系统常量
exports.getSysConstValue = function(req, res) {
    var parameter = req.body;
    var propertyName = parameter.ConstName;

    BaseFun.responseFun(res, null, BaseConst[propertyName]);
};

//获取系统当前时间
exports.getSysDateTime = function(req, res) {
    BaseFun.responseFun(res, null, new Date());
};

exports.getGuids = function(req, res) {
    var parameter = req.body;
    var num = parameter.Num;
    BaseFun.responseFun(res, null, BaseFun.getGuids(num));
};

exports.filesCopy = function(req, res) {
    var parameter = req.body;
    var src = parameter.src;
    var dst = parameter.dst;
    FileCopy(BaseConst.FilePath+src, dst, function(data){
        BaseFun.responseFun(res, null, data);
    },function(error){
        BaseFun.responseFun(res, error, null);
    });
};

exports.filesUnzip = function(req, res) {
    var parameter = req.body;
    var zipPath = parameter.zip;
    var unzipPath = parameter.unzip;
    var unzipExtractor = unzip.Extract({ path: unzipPath });
    fs.createReadStream(zipPath).pipe(unzipExtractor); 
    unzipExtractor.on('error', function(err) {
        BaseFun.responseFun(res, err, null);
    });
    unzipExtractor.on('close', function(){
        BaseFun.responseFun(res, null, 'close');
    });
};

exports.filesZip = function(req, res) {
    var parameter = req.body;
    var path = parameter.path;
    var zipPath = parameter.zipPath;
    var output = fs.createWriteStream(zipPath);
    var archive = archiver('zip');
    output.on('close', function() {
        BaseFun.responseFun(res, null, 'close');
    });

    archive.on('error', function(err) {
        BaseFun.responseFun(res, err, null);
    });

    archive.pipe(output);

    // var file1 = __dirname + '/fixtures/file1.txt';
    // var file2 = __dirname + '/fixtures/file2.txt';

    archive
      // .append(fs.createReadStream(file1), { name: 'file1.txt' })
      // .append(fs.createReadStream(file2), { name: 'file2.txt' })
      .directory(path, false)
      .finalize();
};

